﻿using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;

namespace SwaggerDoc.Api
{
    /// <summary>
    /// 配置swagger生成选项
    /// </summary>
    public class SwaggerConfigureOptions : IConfigureOptions<SwaggerGenOptions>
    {
        private readonly IApiVersionDescriptionProvider provider;

        /// <summary>
        /// SwaggerConfigureOptions
        /// </summary>
        /// <param name="provider"></param>
        public SwaggerConfigureOptions(IApiVersionDescriptionProvider provider) => this.provider = provider;

        /// <summary>
        /// Configure
        /// </summary>
        /// <param name="options"></param>
        public void Configure(SwaggerGenOptions options)
        {
            foreach (var description in provider.ApiVersionDescriptions)
            {
                options.SwaggerDoc(description.GroupName, CreateInfoForApiVersion(description));
            }
        }

        /// <summary>
        /// CreateInfoForApiVersion
        /// </summary>
        /// <param name="description"></param>
        /// <returns></returns>
        private static OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description)
        {
            var info = new OpenApiInfo()
            {
                Title = Assembly.GetEntryAssembly()?.GetName().Name,
                Version = "v" + description.ApiVersion.ToString(),
                Description = description.GroupName,
                Contact = new OpenApiContact
                {
                    Email = "891367701@qq.com",
                    Name = "yanh",
                    Url = new Uri("https://github.com")
                },
                License = new OpenApiLicense
                {
                    Name = "License",
                    Url = new Uri("https://github.com")
                }
            };

            if (description.IsDeprecated)
            {
                info.Description = info.Version + " 版本已弃用尽快升级新版本";
            }

            return info;
        }
    }
}
